package com.zengchen.gateway.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
@Slf4j
public class GlobalFilterConfiguration {

    /**
     * 给每个请求增加个header requestHeader=111111
     * @return
     */
    @Bean
    @Order(1)
    public GlobalFilter addHeaderArPre() {
        return (exchange, chain) -> {
            log.info("do **pre** GlobalFilter addHeaderArPre");
            ServerHttpRequest.Builder requestBuilder = exchange.getRequest().mutate();
            requestBuilder.header("requestHeader","111111");
            ServerWebExchange newExchange = exchange.mutate().request(requestBuilder.build()).build();
            return chain.filter(newExchange).then(Mono.fromRunnable(() -> {
                log.info("do **post** GlobalFilter addHeaderArPre");
            }));
        };
    }

    /**
     * 给每个请求返回的时候，增加header
     * @return
     */
    @Bean
    @Order(2)
    public GlobalFilter addHeaderAtPost() {
        return (exchange, chain) -> {
            log.info("do **pre** GlobalFilter addHeaderAtPost");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("do **post** GlobalFilter addHeaderAtPost");
                exchange.getResponse().getHeaders().add("responseHeader","666666");
            }));
        };
    }
}
